package com.nbjtjc.safe.service.emg;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.emg.EmgGoodsLogMapper;
import com.nbjtjc.safe.mapper.emg.EmgGoodsMapper;
import com.nbjtjc.safe.model.emg.EmgGoods;
import com.nbjtjc.safe.model.emg.EmgGoodsLog;
import com.nbjtjc.safe.model.sys.SysUser;
import com.nbjtjc.safe.util.ExcelUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class EmgGoodsLogService {
    @Autowired
    private EmgGoodsLogMapper emgGoodsLogMapper;

    @Autowired
    private EmgGoodsMapper emgGoodsMapper;

    @Value("${file.path.tempPath}")
    private String goodsLogFilePath;
    public  Result delete(int  emgGoodsLogId){
        Result result=new Result();
        EmgGoodsLog emgGoodsLog=emgGoodsLogMapper.selectByPrimaryKey(emgGoodsLogId);
        if(emgGoodsLog==null||emgGoodsLog.getGoodsId()==null){
            result.setFalse("不能为空");
            return result;
        }
        EmgGoods emgGoods=emgGoodsMapper.selectByPrimaryKey(emgGoodsLog.getGoodsId());
        if(emgGoods==null){
            result.setFalse("该物品不存在");
            return result;
        }
        //先将上次的操作数量复原
        if(emgGoodsLog.getOperationType().equals(Constant.GoodsLogStatus.INSIDE.getValue())){
            emgGoods.setCount(emgGoods.getCount()-emgGoodsLog.getCount());
        }else{
            emgGoods.setCount(emgGoods.getCount()+emgGoodsLog.getCount());
        }
        emgGoodsMapper.updateByPrimaryKeySelective(emgGoods);
        emgGoodsLogMapper.deleteByPrimaryKey(emgGoodsLogId);
        result.setSuccess(true);
        return result;
    }

    @Transactional(rollbackFor = {Throwable.class})
    public Result add(EmgGoodsLog emgGoodsLog) throws Exception {
        Result result=new Result();
        if(emgGoodsLog==null||emgGoodsLog.getGoodsId()==null){
            result.setFalse("不能为空");
            return result;
        }
        EmgGoods emgGoods=emgGoodsMapper.selectByPrimaryKey(emgGoodsLog.getGoodsId());
        if(emgGoods==null){
            result.setFalse("该物品不存在");
            return result;
        }
        if(!checkGoodsOperationValidate(emgGoodsLog)){
            result.setFalse("数量不符合");
            return result;
        }
        if(emgGoodsLog.getOperationType().equals(Constant.GoodsLogStatus.OUTSIDE.getValue())){
            emgGoods.setCount(emgGoods.getCount()-emgGoodsLog.getCount());
        }else{
            emgGoods.setCount(emgGoods.getCount()+emgGoodsLog.getCount());
        }
        SysUser sysUser= (SysUser) SecurityUtils.getSubject().getSession().getAttribute("user");
        emgGoodsLog.setStock(emgGoods.getCount());
        emgGoodsLog.setCreateDate(new Date());
        emgGoodsLog.setRegisterId(sysUser.getUserId());
        int res=emgGoodsLogMapper.insertSelective(emgGoodsLog);
        if(res==0){
            result.setFalse("插入或更新物资操作日志错误");
            return result;
        }
        res=emgGoodsMapper.updateByPrimaryKeySelective(emgGoods);
        if(res==0){
            result.setFalse("更新物资数量失败");
            throw new Exception("更新物资数量失败");
        }
        result.setData(emgGoodsLogMapper.findById(emgGoodsLog.getId()));
        return result;
    }

    @Transactional(rollbackFor = {Throwable.class})
    public Result update(EmgGoodsLog emgGoodsLog) throws Exception {

        Result result=new Result();
        if(emgGoodsLog==null||emgGoodsLog.getGoodsId()==null
                ||emgGoodsLog.getId()==null){
            result.setFalse("不能为空");
            return result;
        }
        EmgGoodsLog lastLog=emgGoodsLogMapper.selectByPrimaryKey(emgGoodsLog.getId());
        if(lastLog==null)
        {
            result.setFalse("没有该记录");
            return result;
        }
        EmgGoods emgGoods=emgGoodsMapper.selectByPrimaryKey(emgGoodsLog.getGoodsId());
        if(emgGoods==null){
            result.setFalse("该物品不存在");
            return result;
        }
        if(!checkGoodsOperationValidate(emgGoodsLog)){
            result.setFalse("数量不符合");
            return result;
        }
        //先将上次的操作数量复原
        if(lastLog.getOperationType().equals(Constant.GoodsLogStatus.OUTSIDE.getValue())){
            emgGoods.setCount(emgGoods.getCount()+lastLog.getCount());
        }else{
            emgGoods.setCount(emgGoods.getCount()-lastLog.getCount());
        }
        //减去这次操作的数量
//        if(emgGoodsLog.getOperationType().equals(Constant.GoodsLogStatus.INSIDE.getValue())){
//            emgGoods.setCount(emgGoods.getCount()+emgGoodsLog.getCount());
//        }else{
//            emgGoods.setCount(emgGoods.getCount()-emgGoodsLog.getCount());
//        }
        if(emgGoodsLog.getOperationType().equals(Constant.GoodsLogStatus.OUTSIDE.getValue())){
            emgGoods.setCount(emgGoods.getCount()-emgGoodsLog.getCount());
        }else{
            emgGoods.setCount(emgGoods.getCount()+emgGoodsLog.getCount());
        }
        emgGoodsLog.setStock(emgGoods.getCount());
        emgGoodsLogMapper.updateByPrimaryKeySelective(emgGoodsLog);
        result.setData(emgGoodsLogMapper.findById(emgGoodsLog.getId()));
        return result;
    }

    public File downGoodsLogFile(Page page, EmgGoodsLog emgGoodsLog) throws IOException {
        List<String> columnsName=new ArrayList<>(Arrays.asList("出/入库"
                ,"日期","物资名称","数量","单位","出入说明","登记人","归还总数","损耗总数","归还日期"));
        List<EmgGoodsLog> emgGoodsLogs=emgGoodsLogMapper.search(emgGoodsLog,page);
        emgGoodsLogs.forEach(log->{
            if(log.getOperationType().equals(0)){
                if(CollectionUtil.isNotEmpty(log.getEntryLogs())){
                    log.getEntryLogs().forEach(entryLog->{
                        log.setEntryAll(log.getEntryAll()+entryLog.getCount());
                        log.setLossAll(log.getLossAll()+entryLog.getLoss());
                    });
                }
            }
        });
        List<List<String>> columnsData=new ArrayList<>();
        for(int i=0;i<columnsName.size();i++){
            columnsData.add(new ArrayList<>());
        }
        int count=emgGoodsLogs.size();
        for(int i=0;i<count;i++){
            columnsData.get(0).add(
                    emgGoodsLogs.get(i).getOperationType().equals(0)?"出库":"入库");
            columnsData.get(1).add(
                    DateUtil.format(emgGoodsLogs.get(i).getCreateDate(),"yyyy-MM-dd"));
            columnsData.get(2).add(emgGoodsLogs.get(i).getGoodsName());
            columnsData.get(3).add(emgGoodsLogs.get(i).getCount().toString());
            columnsData.get(4).add(emgGoodsLogs.get(i).getGoodsUnit());
            columnsData.get(5).add(emgGoodsLogs.get(i).getRemark());
            columnsData.get(6).add(emgGoodsLogs.get(i).getRegisterUser());
            columnsData.get(7).add(emgGoodsLogs.get(i).getEntryAll().toString());
            columnsData.get(8).add(emgGoodsLogs.get(i).getLossAll().toString());
            if(CollectionUtil.isNotEmpty(emgGoodsLogs.get(i).getEntryLogs())){
                columnsData.get(9).add(DateUtil.format(
                        emgGoodsLogs.get(i).getEntryLogs().get(0).getCreateDate()
                        ,"yyyy-MM-dd"
                ));
            }else{
                columnsData.get(9).add("未归还");
            }
        }
        File file= ExcelUtil.getExcelFile(columnsName,columnsData
                ,emgGoodsLogs.size(),goodsLogFilePath+System.currentTimeMillis()+"_物资操作日志.xls");
        return file;
    }

    /**
     * 确认物资操作是否超过数量
     * @param emgGoodsLog
     * @return
     */
    private boolean checkGoodsOperationValidate(EmgGoodsLog emgGoodsLog){
        EmgGoods emgGoods=emgGoodsMapper.selectByPrimaryKey(emgGoodsLog.getGoodsId());
        if(ObjectUtil.isNull(emgGoods)){
            return false;
        }
        if(emgGoodsLog.getOperationType().equals(Constant.EmgGoodsOperation.GOODS_OUT.getValue())){
            if(emgGoodsLog.getCount()>emgGoods.getCount()){
                return false;
            }
        }else if(emgGoodsLog.getOperationType().equals(Constant.EmgGoodsOperation.GOODS_RETURN.getValue())){
            EmgGoodsLog logOut=emgGoodsLogMapper.selectByPrimaryKey(emgGoodsLog.getGoodsLogId());
            if(ObjectUtil.isNull(logOut)){
                return false;
            }
            if((emgGoodsLog.getCount()+emgGoodsLog.getLoss())>logOut.getCount()){
                return false;
            }
        }

        return true;
    }

}
